#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define mes(x) memset(x,0,sizeof(x))
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout)

int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}

template <typename T>
void write(T x){
	bool sgn = 0;
	if(x < 0) x = -x,sgn = 1;
	T stk[20],cnt = 0;
	while(x){
		stk[++cnt] = x%10;
		x/=10;
	}
	if(sgn) putchar('-');
	for(int i = cnt;i >= 1;i--) putchar(stk[i]+48);
	if(cnt == 0) putchar('0');
	putchar('\n');
}

typedef struct {int v,w,nxt;}edge;

const int MAXN = 510;

int m,n,h[MAXN*MAXN],dis[MAXN*MAXN],cnt,dx[4] = {0,-1,0,1},dy[4] = {-1,0,1,0};
char s[MAXN][MAXN];
bool vis[MAXN*MAXN];
edge e[(MAXN*MAXN)<<2];

void link(int x,int y,int w){e[++cnt] = (edge){y,w,h[x]};h[x] = cnt;}

bool IN(int x,int y){return x and y and x <= m and y <= n;}

int id(int x,int y){return (x-1)*n+y;}

int abs(int x){return x<0?-x:x;}

void dijk(){
	priority_queue<pii>q;
	memset(dis,0x3f,sizeof(dis));
	dis[id(1,1)] = 0;
	q.push(pii(0,id(1,1)));
	while(q.size()){
		int x = q.top().se;q.pop();
		if(vis[x]) continue;
		vis[x] = 1;
		for(int i = h[x];i;i = e[i].nxt){
			int y = e[i].v;
			if(dis[y] > dis[x] + e[i].w){
				dis[y] = dis[x] + e[i].w;
				q.push(pii(-dis[y],y));
			}
		}
	}
}

int main (){
	m = in,n = in;
	for(int i = 1;i <= m;i++)
		scanf("%s",s[i]+1);
	for(int i = 1;i <= m;i++)
		for(int j = 1;j <= n;j++){
			if(s[i][j] == 'X') continue;
			int pos;
			if(s[i][j] == 'W') pos = 0;
			if(s[i][j] == 'N') pos = 1;
			if(s[i][j] == 'E') pos = 2;
			if(s[i][j] == 'S') pos = 3;
			for(int k = 0;k < 4;k++){
				int nx = i + dx[k],ny = j + dy[k];
				if(IN(nx,ny)){
					link(id(i,j),id(nx,ny),(k-pos+4)%4);
				}
			}
		}
	dijk();
	if(dis[id(m,n)] == 0x3f3f3f3f) dis[id(m,n)] = -1;
	write(dis[id(m,n)]);
	return 0;
}
